package com.cy.myblog.action.user;

import com.alibaba.fastjson.JSON;
import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.Json;
import com.cy.myblog.pageModel.User;
import com.cy.myblog.service.UserServiceI;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Scope("prototype")
@ParentPackage("basePackage")
@Namespace("/user")
@Action(value = "userAction")
@Results({@Result(name = "success", location = "/jsp/message.jsp"),
	      @Result(name = "fail", location = "/jsp/front/register.jsp"),
	      @Result(name = "logout",type="redirect", location = "/jsp/login.jsp"),
		  @Result(name = "editPage", location = "/jsp/front/edit_user.jsp"),
		  @Result(name = "input",location = "/jsp/front/register.jsp")
	      })
public class UserAction extends BaseAction implements ModelDriven<User>{

	private User user = new User();
	private Json json = null;
	private String userinters;

	@Override
	public User getModel() {
		return user;
	}
	
	private UserServiceI userService;

	@Autowired
	public void setUserService(UserServiceI userService) {
		this.userService = userService;
	}

	public String editUser(){
        Tuser tu = (Tuser)session.get("loginUser");
		if(tu == null){
			return "login";
		}

		BeanUtils.copyProperties(tu,user);
		String[] userinters1 = user.getInterests().split(",");
		for(int i=0;i<userinters1.length;i++)
			userinters1[i] = userinters1[i].trim();
		userinters = JSON.toJSONString(userinters1);
		return "editPage";
	}

	public String update(){
		json = new Json();
		if(user != null){
			try {
				Tuser tu = userService.update(user);
				session.put("loginUser",tu);
			}catch(Exception ex){
				json.setMsg("修改失败!");
				json.setSuccess(false);
				return "editPage";
			}
		}
		json.setMsg("修改成功!");
		json.setSuccess(true);
		json.setRedirectPage("/jsp/index.jsp");
		return "success";
	}

	//ajax验证用户名
	public void checkReg(){
		json = new Json();
		if(userService.getByHql(user.getAccount()) != null){
			json.setMsg("用户名已经存在!");
			json.setSuccess(false);
		}else{
			json.setMsg("可以使用");
			json.setSuccess(true);
		}
		super.writeJson(json);
	}

	//struts2的服务端验证
	public void validateReg(){
		System.out.println(user);
		if(user.getPassword().length() < 6){
			this.addFieldError("password","密码不能少于6位!");
		}
		if(user.getName().length() < 2){
			this.addFieldError("name","昵称必须大于2个字符");
		}

		try {
			Long.parseLong(user.getPhone());
		}catch (NumberFormatException ex){
			this.addFieldError("phone","手机号码必须为数字!");
		}

		try{
			Integer.parseInt(user.getQq());
		}catch(NumberFormatException ex){
			this.addFieldError("qq","QQ号码必须为数字!");
		}
	}

	public String reg(){
		json = new Json();
		try {
			if(StringUtils.isNotBlank(user.getAccount()) && StringUtils.isNotBlank(user.getPassword())){
			    userService.save(user);
			}else{
				json.setMsg("注册失败!账号和密码不能为空");
			    json.setSuccess(false);
			    return "fail";
			}   
		} catch (Exception e) {
			json.setMsg("注册失败!");
			json.setSuccess(false);
			return "fail";
		}
		json.setMsg("注册成功!");
		json.setSuccess(true);
		json.setRedirectPage("/jsp/login.jsp");
		return "success";
	}
	
	public String logout(){
		HttpServletResponse res = ServletActionContext.getResponse();
		HttpServletRequest req = ServletActionContext.getRequest();
		super.clearSession();
		super.removeCookie(res,req,"cookieuser");
		return "logout";
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Json getJson() {
		return json;
	}

	public void setJson(Json json) {
		this.json = json;
	}

	public String getUserinters() {
		return userinters;
	}

	public void setUserinters(String userinters) {
		this.userinters = userinters;
	}
}
